import { ref, set, reactive, toRefs } from 'vue';

// api
import { getTaskDefaultInfo } from '@src/api/TaskApi.ts';

import appConfig from 'app.config';
// util
import { customerAddressSelectConversion } from '@src/util/conversionFunctionUtil.ts';
import fetchMethod from '@src/modules/task/edit/components/TaskEditForm/methods/fetch.js';

export default function useUpdate() {
  const projectProductRef = ref();

  const updateState = reactive({
    form: {},
    allFields: [], // 所有表单字段
    currentSelectCustomerId: '', // 当前选中的客户
  });

  // 获取表单
  const fetchFormField = fields => {
    updateState.allFields = fields;
  };

  /**
   * @description 获取Field
   */
  const getField = type => {
    let field = updateState.allFields.find(item => item.formType == type);
    return field;
  };

  /* form-builder更新事件 */
  const update = ({ field, newValue, oldValue }) => {
    let { fieldName = '', displayName = '' } = field || {};
    if (appConfig.debug) {
      console.info(`[FormBuilder] => ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`);
    }

    if(!field) return
    
    // 选中客户更新联系人和客户地址
    if (field.formType === 'projectCustomer') {
      updateCustomerRelationFields(newValue);
    }
    set(updateState.form, fieldName, newValue);
  };

  // 选择客户更新联系人和客户地址
  const updateCustomerRelationFields = (value, isUpdateProduct = true) => {
    let selectedCustomer = value?.[0] || {};
    let selectedCustomerId = selectedCustomer?.id || selectedCustomer?.value || '';

    // 页面上展示的客户与当前点击的客户一致
    if (selectedCustomerId === updateState.currentSelectCustomerId) return;

    try {
      getTaskDefaultInfo({
        customerId: selectedCustomerId,
      }).then(res => {
        updateState.currentSelectCustomerId = value?.[0]?.id || '';

        let { linkman, address } = res;

        // 重置联系人和地址和产品
        update({ field: getField('linkman'), newValue: [] });
        update({ field: getField('customerAddress'), newValue: [] });
        isUpdateProduct && update({ field: getField('projectProduct'), newValue: [] });

        // 绑定联系人和地址
        linkman && bindLinkman(linkman);
        address && bindAddress(address);
      });
    } catch (error) {
      console.warn('project-type-new: updateCustomerRelationFields -> error', error);
    }
  };

  // 选择产品更新客户&联系人&客户地址
  const updateProduct = async value => {
    updateState.form.product = value;

    try {
      const ret = await fetchMethod.fetchCustomerByProduct({ id: value?.[0].id });

      const customerData = [
        {
          label: ret.customerName,
          value: ret.customerId,
          id: ret.customerId,
        },
      ];

      bindCustomer(customerData);
      updateCustomerRelationFields(customerData, false);

      // 当前客户是空的并第一次选中一个产品的时候过滤同客户的产品
      const selectProductLen = value?.filter(item => item.customerId).length === 1;

      if (selectProductLen) {
        projectProductRef.value?.searchCurrentCustomerProduct();
      }
    } catch (error) {
      console.warn('project-type-new: updateProduct -> error', error);
    }
  };

  /**
   * 绑定客户
   */
  const bindCustomer = value => {
    let field = getField('projectCustomer');
    update({ field: { fieldName: field?.fieldName }, newValue: value });
  };

  /**
   * @description 绑定地址
   * @param {Object} address 地址数据
   */
  const bindAddress = (address = {}) => {
    let field = getField('customerAddress');
    let value = [customerAddressSelectConversion({ ...address })];
    update({ field: { fieldName: field?.fieldName }, newValue: value });
  };

  /**
   * @description 绑定联系人
   * @param {Object} linkman 联系人数据
   */
  const bindLinkman = (linkman = {}) => {
    let field = getField('linkman');
    let value = [
      {
        id: linkman.id,
        name: linkman.name,
        phone: linkman.phone,
      },
    ];
    update({ field: { fieldName: field?.fieldName }, newValue: value });
  };

  return {
    fetchFormField,
    updateState,
    projectProductRef,
    getField,
    update,
    updateProduct,
  };
}
